package com.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.Article;
import com.blog.entity.User;
import com.blog.mapper.ArticleMapper;
import com.blog.service.ArticleService;
import com.blog.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

@Service
public class ArticleServiceImpl implements ArticleService {

    private final ArticleMapper articleMapper;
    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    public ArticleServiceImpl(ArticleMapper articleMapper, UserService userService) {
        this.articleMapper = articleMapper;
        this.userService = userService;
    }

    @Override
    @Transactional
    public Article createArticle(Article article) {
         if (article.getStatus() == null) {
             article.setStatus(0); // 默认待审核
         }
        articleMapper.insert(article);
        return article;
    }

    @Override
    @Transactional
    public Article updateArticle(Article article) {
        logger.info("更新文章前的状态: ID={}, 状态={}", article.getId(), article.getStatus());
        // 设置文章状态为待审核
        article.setStatus(0);
        logger.info("更新文章后的状态: ID={}, 状态={}", article.getId(), article.getStatus());
        // 查询原文章，确认状态变更
        Article originalArticle = articleMapper.selectById(article.getId());
        if (originalArticle != null) {
            logger.info("数据库中原文章状态: ID={}, 状态={}", originalArticle.getId(), originalArticle.getStatus());
        }
        articleMapper.updateById(article);
        // 再次查询，确认更新后的状态
        Article updatedArticle = articleMapper.selectById(article.getId());
        if (updatedArticle != null) {
            logger.info("数据库中更新后文章状态: ID={}, 状态={}", updatedArticle.getId(), updatedArticle.getStatus());
        }
        return article;
    }

    @Override
    @Transactional
    public void deleteArticle(Long id) {
        articleMapper.deleteById(id);
    }

    @Override
    public Article findById(Long id) {
        return articleMapper.findArticleWithDetails(id);
    }

    @Override
    public IPage<Article> findByCategory(Long categoryId, Page<Article> page) {
        return articleMapper.findByCategoryWithDetails(page, categoryId);
    }

    @Override
    public IPage<Article> findByUser(Long userId, Page<Article> page) {
        return articleMapper.findByUserWithDetails(page, userId);
    }

    @Override
    public IPage<Article> findAll(Page<Article> page, Integer status, Long userId, Long categoryId) {
        User user = userService.findById(userId);
        Long filterUserId = null;
        if (user != null && !"ADMIN".equals(user.getRole())) {
            filterUserId = userId;
        }

        IPage<Article> articlesPage = articleMapper.findArticlesWithCategoryName(page, status, filterUserId, categoryId);
        Long total = articleMapper.countArticlesWithCategoryName(status, filterUserId, categoryId);
        articlesPage.setTotal(total);
        return articlesPage;
    }

    @Override
    @Transactional
    public void incrementViewCount(Long id) {
        Article article = articleMapper.selectById(id);
        if (article != null) {
            article.setViewCount(article.getViewCount() + 1);
            articleMapper.updateById(article);
        }
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        Article article = articleMapper.selectById(id);
        if (article != null) {
            article.setStatus(status);
            articleMapper.updateById(article);
        }
    }

    @Override
    public Long countAllArticles(Integer status, Long userId, Long categoryId) {
        User user = userService.findById(userId);
        Long filterUserId = null;
        if (user != null && !"ADMIN".equals(user.getRole())) {
            filterUserId = userId;
        }
        return articleMapper.countArticlesWithCategoryName(status, filterUserId, categoryId);
    }
    
    @Override
    public Long count(Integer status) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        return (long) articleMapper.selectCount(queryWrapper);
    }
    
    @Override
    public List<Map<String, Object>> findTopViewedArticles(Integer limit) {
        QueryWrapper<Article> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1)  // 只统计已发布的文章
                  .orderByDesc("view_count")
                  .last("LIMIT " + limit);
        List<Article> articles = articleMapper.selectList(queryWrapper);
        
        List<Map<String, Object>> result = new ArrayList<>();
        for (Article article : articles) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", article.getId());
            map.put("title", article.getTitle());
            map.put("viewCount", article.getViewCount());
            result.add(map);
        }
        
        return result;
    }
    
    @Override
    public List<Map<String, Object>> getCategoryArticleStats() {
        try {
            logger.info("获取分类文章统计");
            List<Map<String, Object>> stats = articleMapper.getCategoryArticleStats();
            logger.info("分类文章统计获取完成，数量：{}", stats != null ? stats.size() : 0);
            return stats;
        } catch (Exception e) {
            logger.error("获取分类文章统计失败", e);
            return new ArrayList<>();
        }
    }
} 